#!/bin/bash

process=$(ps -ef | grep java |grep -v grep |grep dy-zsj.jar |awk '{print $2}')
if [ "${process}" = "" ]; then
    echo "dy-zsj已经关闭."
else
  echo "dy-zsj进程ID => ${process}，开始停止应用..."

  # 调用 springboot actuator 关闭应用
  curl -X POST http://localhost:9998/actuator/shutdown
  result=$?
  echo "$result"

  i=0 # 计数器
  max_try=30 # 最大等待关闭重试次数
  while true
  do
    if [ $i -gt $max_try ]; then
      echo "循环次数超过 ${max_try} 次，强制关闭应用..."
      kill -9 $process
      sleep 3
      break
    fi

    # 等待应用关闭
    process=$(ps -ef | grep java |grep -v grep |grep dy-zsj.jar |awk '{print $2}')
    if [ "${process}" = "" ]; then
      echo "dy-zsj已经关闭."
      break;
    else
      echo "关闭中，进程ID => $process ..."
      ((i++))
      sleep 1
    fi
  done
fi

app_path=/opt/zsj/dy-zsj

rm -f $app_path/dy-zsj.jar.bak
mv $app_path/dy-zsj.jar $app_path/dy-zsj.jar.bak
cp /opt/zsj/tmp/dy-zsj/dy-zsj.jar $app_path/dy-zsj.jar

bash $app_path/start.sh >> $app_path/start.log 2>&1